import { defineStore } from 'pinia'
import { lawyerAPI } from '@/api/lawyer'
import { caseAPI } from '@/api/case'

/**
 * 律师工作台状态库
 * 管理律师资料、接收案件、更新进度等功能
 */
export const useLawyerStore = defineStore('lawyer', {
  state: () => ({
    // 律师个人资料
    profile: {
      licenseStatus: 'pending', // 'pending'/'approved'
      specialtyAreas: [],
      rating: 0,
      schedule: [] // 日程安排: {date, title, description}
    },
    
    // 分配的待处理案件
    assignedCases: [],
    
    // 已接收的案件
    acceptedCases: [],
    
    // 加载状态
    loading: false,
    
    // 统计信息
    statistics: {
      totalCases: 0,
      pendingCases: 0,
      completedCases: 0,
      monthlyIncome: 0
    }
  }),

  actions: {
    /**
     * 加载律师资料
     */
    async loadProfile() {
      try {
        this.loading = true
        const data = await lawyerAPI.getProfile()
        this.profile = data
        console.log('✅ 律师资料加载成功:', data)
      } catch (error) {
        console.error('❌ 加载律师资料失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    /**
     * 接收新案件
     * @param {string} caseId - 案件ID
     */
    async acceptCase(caseId) {
      try {
        await lawyerAPI.acceptCase(caseId)
        
        // 将案件从未分配列表移到已接受列表
        const caseIndex = this.assignedCases.findIndex(c => c.id === caseId)
        if (caseIndex !== -1) {
          const acceptedCase = this.assignedCases.splice(caseIndex, 1)[0]
          acceptedCase.status = 'processing'
          this.acceptedCases.push(acceptedCase)
        }
        
        console.log('✅ 案件接收成功:', caseId)
      } catch (error) {
        console.error('❌ 接收案件失败:', error)
        throw error
      }
    },

    /**
     * 更新案件进度
     * @param {string} caseId - 案件ID
     * @param {string} status - 新状态
     * @param {string} note - 进度说明
     */
    async updateCaseProgress(caseId, status, note) {
      try {
        await lawyerAPI.updateCaseProgress(caseId, { status, note })
        
        // 更新本地案件状态
        const caseIndex = this.acceptedCases.findIndex(c => c.id === caseId)
        if (caseIndex !== -1) {
          this.acceptedCases[caseIndex].status = status
          this.acceptedCases[caseIndex].progressNote = note
        }
        
        console.log('✅ 案件进度更新成功:', caseId, status)
      } catch (error) {
        console.error('❌ 更新案件进度失败:', error)
        throw error
      }
    },

    /**
     * 添加日程安排
     * @param {Object} event - 日程事件 {date, title, description}
     */
    async addScheduleEvent(event) {
      try {
        const data = await lawyerAPI.addScheduleEvent(event)
        this.profile.schedule.push(data)
        console.log('✅ 日程添加成功:', data)
      } catch (error) {
        console.error('❌ 添加日程失败:', error)
        throw error
      }
    },

    /**
     * 加载分配的待处理案件
     */
    async loadAssignedCases() {
      try {
        this.loading = true
        const data = await lawyerAPI.getAssignedCases()
        this.assignedCases = data
        console.log('✅ 待处理案件加载成功:', data)
      } catch (error) {
        console.error('❌ 加载待处理案件失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    /**
     * 加载已接受的案件
     */
    async loadAcceptedCases() {
      try {
        this.loading = true
        const data = await lawyerAPI.getAcceptedCases()
        this.acceptedCases = data
        console.log('✅ 已接受案件加载成功:', data)
      } catch (error) {
        console.error('❌ 加载已接受案件失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    }
  },

  getters: {
    /**
     * 获取今日日程
     */
    todaySchedule: (state) => {
      const today = new Date().toISOString().split('T')[0]
      return state.profile.schedule.filter(event => event.date === today)
    },

    /**
     * 检查律师是否已通过认证
     */
    isVerified: (state) => state.profile.licenseStatus === 'approved',

    /**
     * 获取待处理案件数量
     */
    pendingCasesCount: (state) => state.assignedCases.length,

    /**
     * 获取已接受案件数量
     */
    acceptedCasesCount: (state) => state.acceptedCases.length,

    /**
     * 获取本周日程
     */
    thisWeekSchedule: (state) => {
      const today = new Date()
      const weekStart = new Date(today.setDate(today.getDate() - today.getDay()))
      const weekEnd = new Date(today.setDate(today.getDate() - today.getDay() + 6))
      
      return state.profile.schedule.filter(event => {
        const eventDate = new Date(event.date)
        return eventDate >= weekStart && eventDate <= weekEnd
      })
    }
  }
}) 